<template>
  <view class="new-container">
    <!-- 简化地图容器 -->
    <view class="simple-map-container">
      <map 
        style="width: 100%; height: 70vh;" 
        :latitude="latitude" 
        :longitude="longitude"
        :markers="markers"
        :scale="16"
        show-location
      ></map>
    </view>

    <!-- 平铺式表单设计 -->
    <view class="flat-form">
      <!-- 地点信息 -->
      <view class="form-item">
        <text class="form-label">地点名称</text>
        <view class="form-value">{{ spotName }}</view>
      </view>
      
      <view class="form-item">
        <text class="form-label">详细地址</text>
        <view class="form-value">{{ address }}</view>
      </view>

      <!-- 时间选择触发按钮 -->
  <view class="form-item time-picker-trigger" @click="showDatetimePicker = true">
    <text class="form-label">预约时间</text>
    <view class="form-value">
      {{ displayTime }}
      <u-icon name="arrow-right" color="#999"></u-icon>
    </view>
  </view>

      <!-- 提交按钮 -->
      <u-button 
        type="primary" 
        shape="square" 
        @click="reserve"
        :disabled="!datetimesingle"
        class="submit-btn"
      >
        立即预约
      </u-button>
    </view>

    <!-- 时间选择器配置 -->
     <u-datetime-picker
       :show="showDatetimePicker"
       v-model="datetimesingle"
       mode="datetime"
       :formatter="formatter"
       @confirm="handleTimeConfirm"
       @cancel="showDatetimePicker = false"
     ></u-datetime-picker>
  </view>
</template>


<script>
	import amapFile from '@/api/amap-wx.js';
	var myAmapFun = new amapFile.AMapWX({
		key: 'ef1e3285d4f509ebe7353c42e6cb7837'
	});

	export default {
		data() {
			return {
				 formatter: (type, value) => {
				      if (type === 'year') {
				        return `${value}年`;
				      }
				      if (type === 'month') {
				        return `${value}月`;
				      }
				      if (type === 'day') {
				        return `${value}日`;
				      }
				      if (type === 'hour') {
				        return `${value}时`;
				      }
				      if (type === 'minute') {
				        return `${value}分`;
				      }
				      return value;
				    },
				    showDatetimePicker: false,
				latitude: 39.91667,
				longitude: 116.41667,
				mapFlafg: false,
				isMapVisible: false, // 控制地图显示
				cardVisible: false, // 控制卡片显示动画
				mapAnimation: false, // 地图动画
				isLoading: false, // 按钮加载状态
				markers: [{
					latitude: 39.91667,
					longitude: 116.41667,
					width: 40,
					height: 40,
					// iconPath: '/static/start.png',
					// callout: {
					// 	content: '目的地',
					// 	color: '#ffffff',
					// 	bgColor: '#762428',
					// 	padding: 5,
					// 	borderRadius: 3,
					// 	display: 'ALWAYS'
					// }
				}],
				isDisabled: false,
				spotName: null,
				address: null,
				userId: 0,
				single: '',
				datetimesingle: '',
				range: ['2021-02-1', '2021-3-28'],
				datetimerange: [],
				start: Date.now() - 1000000000,
				end: Date.now() + 1000000000,
				timeNow: null,
				reserveList: {
					reserveUserId: 0,
					reserveName: null,
					reserveAdress: null,
					reserveTime: null,
					reserveCreateTime: null,
					reserveTag: 1
				}
			}
		},
		  computed: {
		    // 格式化显示的时间
		    displayTime() {
		      if (!this.datetimesingle) return '请选择时间';
		      
		      // 如果是时间戳（number类型）
		      if (typeof this.datetimesingle === 'number') {
		        return this.formatTime(new Date(this.datetimesingle));
		      }
		      
		      // 如果是字符串格式
		      if (typeof this.datetimesingle === 'string') {
		        // 处理ISO格式（如"2023-10-01T14:30:00"）
		        if (this.datetimesingle.includes('T')) {
		          return this.formatTime(new Date(this.datetimesingle));
		        }
		        // 其他格式直接显示
		        return this.datetimesingle;
		      }
		      
		      return '请选择时间';
		    }
		  },
		onLoad(option) {
			// 初始化动画
			this.initAnimations();
			
			// 从缓存获取用户信息
			this.tokenList = uni.getStorageSync("storage_data") || {};
			this.userId = this.tokenList.vuex_id;
			
			// 解析传递过来的数据
			if (option.data) {
				this.parseLocationData(option.data);
			} else {
				this.handleNoLocationData();
			}
		},
		onReady() {
			// 页面准备好后显示地图和卡片
			setTimeout(() => {
				this.isMapVisible = true;
				this.cardVisible = true;
			}, 300);
		},
		methods: {
			    // 统一的时间格式化方法
			    formatTime(date) {
			      const year = date.getFullYear();
			      const month = (date.getMonth() + 1).toString().padStart(2, '0');
			      const day = date.getDate().toString().padStart(2, '0');
			      const hours = date.getHours().toString().padStart(2, '0');
			      const minutes = date.getMinutes().toString().padStart(2, '0');
			      
			      return `${year}-${month}-${day} ${hours}:${minutes}`;
			    },
			    
			    // 修改时间选择确认方法
			    handleTimeConfirm(value) {
			      // 保存原始值（时间戳或ISO字符串）
			      this.datetimesingle = value;
			      this.showDatetimePicker = false;
			    },
			    
			    // 修改预约方法
			    async reserve() {
			      if (!this.datetimesingle) {
			        this.showToast('请选择预约时间');
			        return;
			      }
			      
			      this.isDisabled = true;
			      this.isLoading = true;
			      
			      try {
			        // 准备数据时统一处理时间格式
			        this.prepareReservationData();
			        const res = await this.submitReservation();
			        this.handleReservationResponse(res);
			      } catch (error) {
			        this.handleReservationError(error);
			      } finally {
			        this.isLoading = false;
			      }
			    },
			    
			    // 修改数据准备方法
			    prepareReservationData() {
			      let reserveTime;
			      
			      // 统一处理时间格式
			      if (typeof this.datetimesingle === 'number') {
			        // 时间戳转ISO字符串
			        reserveTime = new Date(this.datetimesingle).toISOString();
			      } else if (this.datetimesingle.includes('T')) {
			        // 已经是ISO格式
			        reserveTime = this.datetimesingle;
			      } else {
			        // 其他格式尝试转换
			        reserveTime = new Date(this.datetimesingle).toISOString();
			      }
			      
			      this.reserveList = {
			        reserveUserId: this.userId,
			        reserveName: this.spotName,
			        reserveAdress: this.address,
			        reserveTime: reserveTime, // 使用ISO格式
			        reserveCreateTime: new Date().toISOString(), // 创建时间也用ISO格式
			        reserveTag: 1
			      };
			    },
			 handleTimeConfirm(value) {
			      this.datetimesingle = value;
			      this.showDatetimePicker = false;
			    },
			initAnimations() {
				this.mapAnimation = uni.createAnimation({
					duration: 500,
					timingFunction: 'ease-in-out'
				});
			},
			parseLocationData(data) {
				try {
					const locationData = JSON.parse(decodeURIComponent(data));
					console.log("接收到的完整数据:", locationData);
					
					this.longitude = locationData.longitude;
					this.latitude = locationData.latitude;
					this.spotName = locationData.address || "未知地点";
					this.address = locationData.detailAddress || locationData.address || "未知地址";
					
					this.updateMapMarker();
					this.mapFlafg = true;
					
				} catch (e) {
					console.error('解析位置数据失败:', e);
					this.showToast('加载位置信息失败');
					this.setDefaultLocation();
				}
			},
			handleNoLocationData() {
				this.showToast('未获取到位置信息');
				this.setDefaultLocation();
			},
			setDefaultLocation() {
				this.longitude = 116.41667;
				this.latitude = 39.91667;
				this.spotName = "默认地点";
				this.address = "北京市东城区";
				this.updateMapMarker();
				this.mapFlafg = true;
			},
			updateMapMarker() {
				this.$set(this.markers[0], "longitude", this.longitude);
				this.$set(this.markers[0], "latitude", this.latitude);
			},
			showToast(title) {
				uni.showToast({
					title: title,
					icon: 'none'
				});
			},
			padZero(num) {
				return num < 10 ? `0${num}` : num;
			},
			async reserve() {
				if (!this.datetimesingle) {
					this.showToast('请选择预约时间');
					return;
				}
				
				this.isDisabled = true;
				this.isLoading = true;
				
				// 准备预约数据
				this.prepareReservationData();
				
				try {
					const res = await this.submitReservation();
					this.handleReservationResponse(res);
				} catch (error) {
					this.handleReservationError(error);
				} finally {
					this.isLoading = false;
				}
			},
			prepareReservationData() {
				this.reserveList.reserveUserId = this.userId;
				this.reserveList.reserveName = this.spotName;
				this.reserveList.reserveAdress = this.address;
				this.reserveList.reserveTime = this.datetimesingle;
				
				const now = new Date();
				this.reserveList.reserveCreateTime = 
					`${now.getFullYear()}-${this.padZero(now.getMonth() + 1)}-${this.padZero(now.getDate())} ` +
					`${this.padZero(now.getHours())}:${this.padZero(now.getMinutes())}:${this.padZero(now.getSeconds())}`;
			},
			async submitReservation() {
				return new Promise((resolve, reject) => {
					uni.request({
						url: this.$BASE_URL.baseUrl + '/mine/reserve',
						method: 'POST',
						header: {
							'Content-Type': 'application/json',
							'Authorization': this.tokenList.vuex_token || ''
						},
						data: this.reserveList,
						success: resolve,
						fail: reject
					});
				});
			},
			handleReservationResponse(res) {
				if (res.statusCode === 200) {
					this.showToast('预约成功');
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} else {
					this.showToast(res.data.message || '预约失败');
					this.isDisabled = false;
				}
			},
			handleReservationError(error) {
				console.error('预约请求失败:', error);
				this.showToast('网络错误，请重试');
				this.isDisabled = false;
			},
			changeLog(e) {
				console.log('时间选择变更:', e);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.new-container {
	  display: flex;
	  flex-direction: column;
	  height: 100vh;
	}
	
	.simple-map-container {
	  height: 70vh;
	  width: 100%;
	}
	
	.flat-form {
	  padding: 30rpx;
	  background: #fff;
	  flex: 1;
	  box-shadow: 0 -5rpx 20rpx rgba(0,0,0,0.05);
	}
	
	.form-item {
	  padding: 25rpx 0;
	  border-bottom: 1rpx solid #f5f5f5;
	  display: flex;
	  justify-content: space-between;
	  
	  .form-label {
	    color: #666;
	    font-size: 30rpx;
	  }
	  
	  .form-value {
	    color: #333;
	    font-size: 32rpx;
	    display: flex;
	    align-items: center;
	    
	    &.placeholder {
	      color: #999;
	    }
	  }
	}
	
	.time-picker-trigger {
	  .form-value {
	    color: #762428;
	  }
	}
	
	.submit-btn {
	  margin-top: 50rpx;
	  height: 90rpx;
	  font-size: 34rpx;
	  background: #762428;
	  
	  &[disabled] {
	    background: #ccc !important;
	  }
	}
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
	}
	
	/* 地图容器样式 */
	.map-container {
		width: 100%;
		height: 60vh;
		position: relative;
		overflow: hidden;
		border-radius: 0 0 20rpx 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	}
	
	/* 地图加载占位图 */
	.map-placeholder {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: #f0f0f0;
		
		.loading-gif {
			width: 120rpx;
			height: 120rpx;
			margin-bottom: 20rpx;
		}
		
		.loading-text {
			font-size: 28rpx;
			color: #666;
		}
	}
	
	/* 预约卡片容器 */
	.reservation-card-container {
		padding: 20rpx;
		margin-top: -40rpx;
		z-index: 10;
	}
	
	/* 预约卡片样式 */
	.reservation-card {
		border-radius: 16rpx;
		box-shadow: 0 8rpx 30rpx rgba(118, 36, 40, 0.15);
		transform: translateY(50rpx);
		opacity: 0;
		transition: all 0.5s ease-out;
		
		&.card-visible {
			transform: translateY(0);
			opacity: 1;
		}
	}
	
	/* 位置信息样式 */
	.location-info {
		display: flex;
		flex-direction: column;
		
		.spot-name {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 12rpx;
			line-height: 1.4;
		}
		
		.address {
			font-size: 28rpx;
			color: #666;
			line-height: 1.4;
		}
	}
	
	/* 预约按钮样式 */
	.reservation-btn {
		height: 90rpx;
		border-radius: 12rpx;
		background-color: #762428;
		color: #fff;
		font-size: 32rpx;
		transition: all 0.3s;
		
		&:active {
			opacity: 0.8;
			transform: scale(0.98);
		}
		
		&[disabled] {
			background-color: #ccc;
		}
	}
	
	/* 时间选择器容器 */
	.datetime-picker-container {
		margin-top: 30rpx;
	}
	
	/* 自定义时间选择器样式 */
	.custom-datetime-picker {
		::v-deep .uni-date-editor--x {
			border: 1px solid #eee;
			border-radius: 12rpx;
			padding: 20rpx;
		}
		
		::v-deep .uni-date__x-input {
			font-size: 28rpx;
			color: #333;
		}
		
		::v-deep .uni-icons {
			color: #762428;
		}
	}
</style>